<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="700px"
    >
      <el-form
        :model="teacherForm"
        :rules="teacherFormRules"
        ref="teacherForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名：" prop="realName">
              <el-input
                v-model="teacherForm.realName"
                placeholder="请输入姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号：" prop="username">
              <el-input
                v-model="teacherForm.username"
                placeholder="请输入账号"
                clearable
                :disabled="mode === 'editTeacher'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别：" prop="sex">
              <el-select v-model="teacherForm.sex" placeholder="请选择性别">
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄：" prop="age">
              <el-input
                v-model="teacherForm.age"
                placeholder="请输入年龄"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系方式：" prop="mobile">
              <el-input
                v-model="teacherForm.mobile"
                placeholder="请输入联系方式"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位：" prop="position">
              <el-cascader
                :options="selectEnums.jobOptions"
                :props="jobOptionsProps"
                clearable
                v-model="teacherForm.positionAncestor"
                collapse-tags
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授课年级：" prop="grade">
              <nice-select
                v-model="teacherForm.grade"
                placeholder="请选择授课年级"
                clearable
                :options="selectEnums.grade"
                labelkey="name"
                valuekey="id"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学科：" prop="subjects">
              <nice-select
                v-model="teacherForm.subjects"
                placeholder="请选择学科"
                clearable
                multiple
                :options="selectEnums.subject"
                labelkey="name"
                valuekey="id"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="dataFormSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { tableInsert, tableUpdate } from '@/api/api.js'
import { queryAutoSqlOne } from '@/api/user'
import { adminschoolteachersave } from '@/api/lcmapi.js'
export default {
  data () {
    const validateMobile = (rule, value, callback) => {
      if (!this.$valid.isMobile(value) && value) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      teacherForm: {
        realName: '',
        sex: '',
        username: '',
        age: '',
        mobile: '',
        position: '',
        grade: '',
        subject: '',
        positionAncestor: []
      },
      jobOptionsProps: {
        checkStrictly: true,
        value: 'nodeId',
        label: 'nodeName'
      },
      title: '',
      teacherId: '',
      teacherFormRules: {
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        age: [
          { required: true, message: '年龄不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value) {
                if (!/^([1-9][0-9]{0,1}|100)$/.test(value)) {
                  callback('请输入1到100之间的数字！') //eslint-disable-line
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],

        sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        grade: [
          { required: true, message: '授课年级不能为空', trigger: 'change' }
        ],
        subjects: [
          { required: true, message: '学科不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    'teacherForm.subjects' (val) {
      if (!val) {
        this.teacherForm.subjects = ''
      } else if (typeof val === 'string') {
        this.teacherForm.subjects = val.split(',').map(item => +item)
      }
    }
  },
  props: {
    mode: '',
    schoolId: '',
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    gradeList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    init (obj) {
      this.visible = true
      this.title = this.mode === 'addTeacher' ? '新增教师' : '编辑教师'
      this.$nextTick(() => {
        this.$refs['teacherForm'].resetFields()
        if (!obj) {
          this.teacherForm = {
            realName: '',
            sex: '',
            username: '',
            age: '',
            mobile: '',
            position: '',
            grade: '',
            subject: '',
            positionAncestor: [],
            isUpdate: false
          }
          return
        }

        if (obj) {
          console.log(obj)
          this.teacherForm = obj
          this.teacherForm.isUpdate = true
          try {
            this.teacherForm.positionAncestor = [
              ...this.teacherForm.positionAncestor.split('$'),
              this.teacherForm.positionId
            ]
            this.teacherForm.positionAncestor.splice(0, 2)
            this.teacherForm.positionAncestor = this.teacherForm.positionAncestor
              .filter(item => item)
              .map(item => +item)
            console.log(this.teacherForm.positionAncestor)
          } catch (error) {
            this.teacherForm.positionAncestor = ''
          }
        }
      })
    },
    async queryAutoSqlOne () {
      let res = await queryAutoSqlOne({
        table_name: 'nice_school_teacher',
        teacher_id: this.teacherId
      })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.teacherForm = {
          realName: res[1].data.name,
          sex: res[1].data.sex === 2 ? '' : res[1].data.sex,
          username: res[1].data.account,
          age: res[1].data.age,
          mobile: res[1].data.phone,
          position: res[1].data.position,
          grade: res[1].data.grade,
          subject: res[1].data.subject
        }
      } else {
        this.$message.error(res[1].msg)
      }
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['teacherForm'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async submit () {
      let argObj = {
        schoolId: this.schoolId,
        username: this.teacherForm.username,
        realName: this.teacherForm.realName,
        sex: this.teacherForm.sex,
        age: this.teacherForm.age,
        mobile: this.teacherForm.mobile,
        subject: this.teacherForm.subject,
        subjects: this.teacherForm.subjects.join(','),
        grade: this.teacherForm.grade,
        positionId: this.teacherForm.positionAncestor[
          this.teacherForm.positionAncestor.length - 1
        ],
        position: this.teacherForm.position,
        isUpdate: this.teacherForm.isUpdate
      }
      if (!this.teacherForm.mobile) {
        delete argObj.mobile
      }
      let res = await adminschoolteachersave(argObj)
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message:
            this.mode === 'addTeacher' ? '新增教师成功！' : '编辑教师成功！',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
